package com.lxh.config.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import io.minio.PutObjectOptions;
import org.xmlpull.v1.XmlPullParserException;

import io.minio.MinioClient;
import io.minio.errors.MinioException;

/**
 * @author mrlee
 */
public class FileUploader {
    public static void main(String[] args) throws NoSuchAlgorithmException, IOException, InvalidKeyException, XmlPullParserException {
        uploadFile();
    }

    private static void uploadFile() throws InvalidKeyException, IOException, NoSuchAlgorithmException {
        try {
            //你的endpoint,本机可以不变
            String endpoint = "http://localhost:9000";
            //你的accessKey
            String accessKey = "U9L1St0L7pUc32CH";
            //你的sercetKey
            String secretKey = "h5GswJXunONPlvVbLiMfWJAyMk9AgIkM";
            //你的bucket
            String bucketName = "lxh";
            // 使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
            MinioClient minioClient = new MinioClient(endpoint, accessKey, secretKey);

            // 检查存储桶是否已经存在
            boolean isExist = minioClient.bucketExists(bucketName);
            if (isExist) {
                System.out.println("Bucket already exists.");
            } else {
                // 创建一个名为asiatrip的存储桶，用于存储照片的zip文件。
                minioClient.makeBucket(bucketName);
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
            String date = sdf.format(new Date());
            //找一个你电脑上图片的绝对路径,最好是PNG图片
            File file = new File("C:\\Users\\lenovo\\Desktop\\favicon.jpg");
            long size = file.length();
            String fileName = file.getName();
            InputStream is = new FileInputStream(file);
            //将待上传的文件的路径设置成 年/月/日/uuid+file01.png
            //你也可以自定义上传文件的路径，这样设置是为了更好的管理
            String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 6);
            String fileUploadPath = date + uuid + "file01" + fileName.substring(fileName.lastIndexOf("."));

            PutObjectOptions options = new PutObjectOptions(size, -1);
            //设置图片的contentType，如果不是PNG图片就自行修改对应的contentType,这样做的目的是为了上传之后访问图片时可以在浏览器预览而不用下载，当然也可以注释这行代码
            options.setContentType("image/png");

            minioClient.putObject(bucketName, fileUploadPath, is, options);

            System.out.println(file.getAbsolutePath() + "is successfully uploaded as 【" + fileUploadPath + "】 to 【" + bucketName + "】bucket.");
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
        }
    }
}
